<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=
  , initial-scale=1.0"
    />
    <title>Document</title>
  </head>
  <body>
    <div id="test"></div>
    <div id="test1"></div>
    <div id="test2"></div>

    <script
      src="https://unpkg.com/react@16/umd/react.development.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
      crossorigin
    ></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </body>
  <script type="text/babel">
    //创建组件
    //生命周期回调函数<=>生命周期钩子函数<=>生命周期函数<=>生命周期钩子
    class Life extends React.Component {
      state = { opacity: 1 };
      death = () => {
        //卸载组件
        ReactDOM.unmountComponentAtNode(document.getElementById("test"));
      };
      //组件挂载完毕
      componentDidMount() {
        this.timer = setInterval(() => {
          let { opacity } = this.state;
          //减少0.1
          opacity -= 0.1;
          if (opacity <= 0) opacity = 1;
          //设置新的透明度
          this.setState({ opacity });
        }, 200);
      }
      //组件将要卸载
      componentWillUnmount() {
        //清除定时器
        clearInterval(this.timer);
      }
      //render调用时机：初始化渲染、状态更新之后
      render() {
        return (
          <div>
            <h2 style={{ opacity: this.state.opacity }}>React学不会怎么半 </h2>
            <button onClick={this.death}>不活了</button>
            <button onClick={this.change}>开始变化</button>
          </div>
        );
      }
    }

    //渲染组件到页面
    ReactDOM.render(<Life />, document.getElementById("test"));
  </script>
</html>
